package likou;

import java.util.*;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/07/16 10:19
 */
public class _1932 {
    public TreeNode canMerge(List<TreeNode> trees) {
        Map<Integer,int[]> map = new HashMap<>();
        Set<Integer> set = new HashSet<>();

        for(int i=0;i<trees.size();i++){
            TreeNode node = trees.get(i);
            set.add(i);
            if(node.left!=null){
                map.put(node.left.val,new int[]{i,1});
            }
            if(node.right!=null){
                map.put(node.right.val,new int[]{i,2});
            }
        }

        for (TreeNode node : trees) {
            int[] nums = map.get(node.val);
            if (nums == null) {
                return null;
            }
            if (nums[1] == 1) {
                trees.get(nums[0]).left = node;
            } else {
                trees.get(nums[0]).right = node;
            }
            set.remove(nums[0]);
        }
        if (set.size()!=1){
            return null;
        }
        for (Integer integer : set) {
            return trees.get(integer);
        }
        return null;
    }
}
